<template>
  <div>
    <!-- 弹层组件 -->
    <el-dialog :title="title" :visible="showDialog" @close="close">
      <!-- 表单组件 -->
      <el-form ref="form" label-width="100px" :model="Form" :rules="rules">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="Form.name" placeholder="2-10个字符" style="width: 80%" size="mini" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="Form.code" placeholder="2-10个字符" style="width: 80%" size="mini" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="managerId">
          <el-select v-model="Form.managerId" placeholder="请选择负责人" style="width: 80%" size="mini">
            <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="Form.introduce" type="textarea" placeholder="1-100个字符" style="width: 80%" size="mini" :rows="4" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center" />
          <el-col :span="12">
            <el-button type="primary" @click="confirm">确定</el-button>
            <el-button @click="close">取消</el-button>
          </el-col>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getManagerList, getDepartments, addDepartment, getDepartDetail, updateDepart } from '@/api/department'

export default {
  name: 'AddDept',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    currentId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      Form: {
        code: '',
        introduce: '',
        managerId: '',
        name: '',
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              // 需求：新增部门
              // 1.查询所有的部门列表数据
              // 2.判断当前输入的部门名称是否在列表中存在
              // 2.1 存在，提示部门名称已存在
              // 2.2 不存在，校验通过
              let res = await getDepartments()
              if (this.Form.id) {
                res = res.filter(item => item.id !== this.Form.id)
              }
              // some → 只要有一项有满足条件，返回true
              // every → 所有的项都要满足条件，返回true
              // find → 只要有一项有满足条件，返回这个项
              if (res.some(item => item.name === value)) {
                callback(new Error('部门名称已存在'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              // 需求：新增部门
              // 1.查询所有的部门列表数据
              // 2.判断当前输入的部门名称是否在列表中存在
              // 2.1 存在，提示部门名称已存在
              // 2.2 不存在，校验通过
              let res = await getDepartments()
              if (this.Form.id) {
                res = res.filter(item => item.id !== this.Form.id)
              }
              // some → 只要有一项有满足条件，返回true
              // every → 所有的项都要满足条件，返回true
              // find → 只要有一项有满足条件，返回这个项
              if (res.some(item => item.code === value)) {
                callback(new Error('部门编码已存在'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        managerId: [
          { required: true, message: '请选择部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ]
      },
      managerList: []
    }
  },
  computed: {
    title() {
      return this.Form.id ? '编辑部门' : '添加部门'
    }
  },
  created() {
    this.getManagerList()
  },
  methods: {
    close() {
      this.Form = {
        code: '',
        introduce: '',
        managerId: '',
        name: '',
        pid: ''
      }
      // 重置表单
      this.$refs.form.resetFields()
      // 通知父组件关闭弹层
      this.$emit('update:showDialog', false)
    },
    // 获取部门负责人列表
    async getManagerList() {
      const res = await getManagerList()
      console.log(res)
      this.managerList = res
    },
    // 获取部门详情
    async getDepartmentDetail() {
      this.Form = await getDepartDetail(this.currentId)
    },
    // 确认按钮
    async confirm() {
      // 1.验证表单
      await this.$refs.form.validate()
      // 2.调用接口
      if (this.Form.id) {
        await updateDepart(this.Form)
        this.$message.success('修改部门成功')
      } else {
        await addDepartment({ ...this.Form, pid: this.currentId })
        // 3.提示用户
        this.$message.success('新增部门成功')
      }
      // 4.通知父组件更新
      this.$emit('updateDepartments')
      // 5.重置表单+关闭弹层
      this.close()
    }
  }
}
</script>
